package com.diary.database;

import com.diary.DBUtils;

import java.sql.*;

public class CreateDiary {
    //现已弃用，使用CreateTable，名称更贴切

    // 查找是否有数据表，如果有，就进行新建日记
    public static boolean select(String username) {

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        DatabaseMetaData dbMetaData = null;

        try {
            connection = DBUtils.getConnection();
            dbMetaData = connection.getMetaData();


            resultSet = dbMetaData.getTables(null, null, username, null);

//            String sql = "SHOW TABLES LIKE ?";

//            preparedStatement = connection.prepareStatement(sql);

//            preparedStatement.setString(1,username);

//            resultSet = preparedStatement.executeQuery();



//            System.out.println("查询表名");
//            System.out.println(resultSet.next());

            return resultSet.next();


        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        finally {
            DBUtils.close(resultSet,preparedStatement, connection);
        }
    }





    //如果没有，就先创建数据表
    public static boolean create(String username) {

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        String tablename = username;

        try {
            connection = DBUtils.getConnection();

            String sql = "CREATE TABLE " + username + " (" +
                    "    id INT AUTO_INCREMENT PRIMARY KEY," +
                    "    diary_title VARCHAR(50) NOT NULL," +
                    "    diary_body VARCHAR(15000)," +
                    "    data_time VARCHAR(50) NOT NULL," +
                    "    accepted VARCHAR(50) NOT NULL, " +
                    "    life INT NOT NULL DEFAULT 0" +
                    ")";
            preparedStatement = connection.prepareStatement(sql);

            preparedStatement.setString(1,username);

            resultSet = preparedStatement.executeQuery();

            return resultSet.next();


        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        finally {
            DBUtils.close(resultSet,preparedStatement, connection);
        }
    }
}




